import React, { useMemo, useState } from "react";
import { InboxOutlined } from "@ant-design/icons";
import { Upload } from "antd";
import { getToken } from "@/utils/auth";
import useMyContext from "@/hooks/useContext";
import { convertImgUrl } from "@/utils/MyFun";
import styled from "styled-components";

const Styled = styled.div`
  img {
    &:hover {
      cursor: pointer;
    }
  }
`;
const { Dragger } = Upload;

const UploadOne = (props) => {
  const { messageApi } = useMyContext();
  // preview组件传入的图片地址，初始为空
  const { width = 120, preview, UpdateFormModel } = props;
  const [previewImg, setPreviewImg] = useState(preview);

  const token = getToken();
  const imgUrl = useMemo(() => {
    return convertImgUrl(previewImg);
  }, [previewImg]);

  return (
    <Styled>
      {previewImg ? (
        <img
          alt="文章封面"
          style={{
            width: `${width}px`,
            border: "1px dashed #d9d9d9",
            borderRadius: "5px",
          }}
          src={imgUrl}
        />
      ) : (
        <Dragger
          name="file"
          //自动往后端该接口请求
          action="/api/upload"
          headers={{ Authorization: `Bearer ${token}` }}
          onChange={(info) => {
            const { status } = info.file;

            if (status === "done") {
              const response = info.file.response; //后端返回的结果
              if (response.code !== 0) {
                //上传错误执行
                messageApi.error(response.message);
                return;
              }
              const filepath = response.data;
              setPreviewImg(filepath);
              // 触发父组件更新保存图片地址
              UpdateFormModel({ img: filepath });
            } else if (status === "error") {
              messageApi.error(`${info.file.name} file upload failed.`);
            }
          }}
          showUploadList={false}
          style={{ width: `75%` }}
        >
          <p className="ant-upload-drag-icon">
            <InboxOutlined />
          </p>
          <p className="ant-upload-text">点击或者拖动文件到该区域来上传</p>
        </Dragger>
      )}
    </Styled>
  );
};

export default UploadOne;
